package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.Review;
import com.bookstore.mapper.ReviewMapper;
import com.bookstore.service.ReviewService;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Override
    public boolean addReview(Review review) {
        // 设置初始状态为待审核
        review.setStatus(0);
        review.setLikes(0);
        return save(review);
    }

    @Override
    public boolean updateReview(Review review) {
        // 更新时不允许修改状态和点赞数
        Review existingReview = getById(review.getReviewId());
        if (existingReview == null) {
            throw new IllegalArgumentException("评论不存在");
        }
        review.setStatus(existingReview.getStatus());
        review.setLikes(existingReview.getLikes());
        return updateById(review);
    }

    @Override
    public boolean deleteReview(Integer reviewId) {
        return removeById(reviewId);
    }

    @Override
    public List<Review> getBookReviews(Integer bookId) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Review::getBookId, bookId)
                .eq(Review::getStatus, 1) // 只查询已通过的评论
                .orderByDesc(Review::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public List<Review> getUserReviews(Integer userId) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Review::getUserId, userId)
                .orderByDesc(Review::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public boolean reviewStatus(Integer reviewId, Integer status) {
        if (status != 1 && status != 2) {
            throw new IllegalArgumentException("无效的状态值");
        }
        Review review = getById(reviewId);
        if (review == null) {
            throw new IllegalArgumentException("评论不存在");
        }
        review.setStatus(status);
        return updateById(review);
    }

    @Override
    public boolean likeReview(Integer reviewId) {
        Review review = getById(reviewId);
        if (review == null) {
            throw new IllegalArgumentException("评论不存在");
        }
        review.setLikes(review.getLikes() + 1);
        return updateById(review);
    }
} 